# -*- coding: utf-8 -*-
#!/usr/bin/python
# @Date : 2021-08-28
# @Author : zhu
# @File : utils.py
# @Software: VS
import hashlib
import random
import json
from PIL import Image, ImageDraw, ImageFont
#from django.utils.six import BytesIO
from io import BytesIO
from django.http import HttpResponse
from django.conf import settings
from random import choice
from common.py_redis import PyRedis
from django.http import HttpResponseRedirect
from django.urls import reverse
import os
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
from index.models import VisitInfo

base_path = Path(__file__).parent

def visitInfo(request,log=None,url_name=None):
    try:
        kwargs = {'ip':request.META.get('REMOTE_ADDR'),'detail':request.headers['User-Agent'],'url':url_name}
        obj, created = VisitInfo.objects.update_or_create(**kwargs)
        if not created:
            obj.count += 1
            obj.save()
    except Exception as e:
        if log:log.error(str(e))

# 校验登录
def check_login(fun):
    def wrap(request, *args, **kwargs):
        if not request.username:
            return HttpResponseRedirect(reverse('user_login'))
        else:
            return fun(request, *args, **kwargs)
    return wrap

# 返回方法
def Response(result=1,data=None,msg=None):
    data = {
        'result':result,
        'data':data,
        'msg':msg
    }
    return HttpResponse(json.dumps(data),content_type='application/json')
    
# 获取md5加密
def get_md5(chars):
    obj = hashlib.md5(chars.encode('utf8'))
    return obj.hexdigest()

def generate_code_all():
    """
    生成六位随机字符串code
    """
    seeds = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
    random_str = []
    for i in range(4):
        random_str.append(choice(seeds))
    return "".join(random_str)

# 密码与盐组合算法
def pwd_salt(pwd,salt):
    pwd = pwd[:10] + salt[:2] + pwd[10:]+ salt[2:]
    return pwd

# 验证码验证
def code(code_key,code):
    try:
        redis = PyRedis()
        save_code = redis.get(code_key)
        if save_code != code.lower():
            return False
        redis.delete(code_key)
        return True
    except Exception as e:
        return False


# 验证码
def varify_code():
    r = random.randrange(0,255)
    g = random.randrange(0,255,30)
    b = random.randrange(0,255,40)
    bgcolor =(r,g,b)
    width = 100
    heigth = 25
    im = Image.new('RGB',(width,heigth),bgcolor)
    draw = ImageDraw.Draw(im)
    for i in range(100):
        r = random.randrange(0,255)
        g = random.randrange(0,255,30)
        b = random.randrange(0,255,40)
        x = random.randrange(1,width)
        y = random.randrange(1,heigth)
        xy = (x,y)
        fill = (b,g,r)
        draw.point(xy, fill=fill)
    code = generate_code_all()
    font = ImageFont.truetype(str(base_path.parent / 'font/DejaVuSansCondensed-Bold.ttf'), 20)
    fontcolor = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255))
    draw.text((random.randrange(0, 8), 2), code[0], font=font, fill=fontcolor)
    draw.text((random.randrange(35, 50), 2), code[2], font=font, fill=fontcolor)
    fontcolor = (random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255))
    draw.text((random.randrange(18, 30), 2), code[1], font=font, fill=fontcolor)
    draw.text((random.randrange(55, 80), 2), code[3], font=font, fill=fontcolor)
    del draw        
    buf = BytesIO()
    im.save(buf, 'png')
    return code,buf

# 获取随机密码
def get_random_pwd(num=10):
    pwd = ''
    key1 = 'QWERTYUIOPASDFGHJKLZXCVBNM'
    key2 = 'qwertyuiopasdfghjklzxcvbnm'
    key3 = '!@#$%^&*><?~-=_+'
    key4 = '1234567890'
    pwd += ''.join(random.sample(key1,10))+''.join(random.sample(key2,10))
    pwd += ''.join(random.sample(key3,8))+''.join(random.sample(key4,2))
    pwd = ''.join(random.sample(pwd,num))
    return pwd


